package com.example.controller;

import com.example.constant.RedisConstant;
import com.example.model.FraudRiskResult;
import com.example.model.Result;
import com.example.model.pojo.LoginLog;
import com.example.model.pojo.OperationLog;
import com.example.model.pojo.PaymentRecord;
import com.example.model.pojo.TransferRecord;
import com.example.service.FraudDetectionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 社保欺诈风险检测控制器
 * 
 * @author system
 */
@RestController
@RequestMapping("/fraud")
@Api(tags = "社保欺诈风险检测接口")
@RequiredArgsConstructor
@Slf4j
public class FraudDetectionController {

  private final FraudDetectionService fraudDetectionService;

  private final RedisTemplate<String, Object> redisTemplate;

  /**
   * 实时风险检测
   * 
   * @param userAddress 用户地址
   * @return 风险检测结果
   */
  @ApiOperation("实时风险检测")
  @PostMapping("/realtime")
  public Result<FraudRiskResult> realtimeCheck(@RequestBody String userAddress) {
    log.info("收到实时风险检测请求，用户地址：{}", userAddress);
    FraudRiskResult result = fraudDetectionService.detectRealTime(userAddress);
    return Result.success(result);
  }

  /**
   * 身份冒用风险检测
   * 
   * @param userAddress   用户地址
   * @param operationLogs 操作日志
   * @param loginLogs     登录日志
   * @return 风险检测结果
   */
  @ApiOperation("身份冒用风险检测")
  @PostMapping("/identity-theft")
  public Result<FraudRiskResult> identityTheftCheck(
      @RequestParam String userAddress,
      @RequestBody(required = false) List<OperationLog> operationLogs,
      @RequestBody(required = false) List<LoginLog> loginLogs) {
    log.info("收到身份冒用风险检测请求，用户地址：{}", userAddress);
    FraudRiskResult result = fraudDetectionService.detectIdentityTheft(userAddress, operationLogs, loginLogs);
    return Result.success(result);
  }

  /**
   * 资金异常风险检测
   * 
   * @param userAddress    用户地址
   * @param paymentRecords 缴费记录
   * @return 风险检测结果
   */
  @ApiOperation("资金异常风险检测")
  @PostMapping("/financial-anomaly")
  public Result<FraudRiskResult> financialAnomalyCheck(
      @RequestParam String userAddress,
      @RequestBody(required = false) List<PaymentRecord> paymentRecords) {
    log.info("收到资金异常风险检测请求，用户地址：{}", userAddress);
    FraudRiskResult result = fraudDetectionService.detectFinancialAnomaly(userAddress, paymentRecords);
    return Result.success(result);
  }

  /**
   * 地域冲突风险检测
   * 
   * @param userAddress     用户地址
   * @param transferRecords 转移记录
   * @param loginLogs       登录日志
   * @return 风险检测结果
   */
  @ApiOperation("地域冲突风险检测")
  @PostMapping("/location-conflict")
  public Result<FraudRiskResult> locationConflictCheck(
      @RequestParam String userAddress,
      @RequestBody(required = false) List<TransferRecord> transferRecords,
      @RequestBody(required = false) List<LoginLog> loginLogs) {
    log.info("收到地域冲突风险检测请求，用户地址：{}", userAddress);
    FraudRiskResult result = fraudDetectionService.detectLocationConflict(userAddress, transferRecords, loginLogs);
    return Result.success(result);
  }

  /**
   * 批量风险检测（手动触发）
   * 
   * @return 风险检测结果列表
   */
  @ApiOperation("批量风险检测")
  @PostMapping("/batch")
  public Result<List<FraudRiskResult>> batchDetection() {
    log.info("收到批量风险检测请求");

    // 检查Redis缓存
    String cacheKey = RedisConstant.FRAUD_BATCH_DETECTION;
    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
    List<FraudRiskResult> cachedResults = (List<FraudRiskResult>) valueOperations.get(cacheKey);
    if (cachedResults != null && !cachedResults.isEmpty()) {
      log.info("从缓存获取批量风险检测结果");
      return Result.success(cachedResults);
    }

    // 执行原逻辑
    List<FraudRiskResult> results = fraudDetectionService.batchDetection();

    // 存入Redis缓存，设置1小时过期时间
    valueOperations.set(cacheKey, results, 1, TimeUnit.HOURS);
    log.info("批量风险检测结果已缓存");

    return Result.success(results);
  }

  /**
   * 生成风险报告
   * 
   * @param address 用户地址
   * @return 风险报告
   */
  @ApiOperation("生成风险报告")
  @GetMapping("/risk-report/{address}")
  public Result<FraudRiskResult> generateReport(@PathVariable String address) {
    log.info("收到生成风险报告请求，用户地址：{}", address);
    FraudRiskResult result = fraudDetectionService.detectRealTime(address);
    return Result.success(result);
  }
}